﻿#region

using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Vin.Tool.AspNetCore.Options;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.NetCategory;

#endregion

namespace Vin.AspNetCore.Core.Middleware;

public class VinAppEntryMiddleware(RequestDelegate next)
{
    public async Task Invoke(HttpContext context)
    {
        context.GenerateRequestId();

        // 判断是否是流式返回的路由地址
        var vinOption = VinApp.GetOption<VinOption>();
        if (context.Request.Path.HasValue && vinOption.StreamResponseRoutes.Any(m =>
                Regex.IsMatch(context.Request.Path.Value.ToLower(), m.ToLower(), RegexOptions.IgnoreCase)))
        {
            // 如果是流式返回的路由地址，则直接放行
            await next(context);
            return;
        }

        #region 请求体可读

        context.Request.EnableBuffering();

        #endregion

        #region 定义响应流

        var originalBodyStream = context.Response.Body;
        using var memoryStream = new MemoryStream();
        context.Response.Body = memoryStream;

        await next(context);

        // 将响应内容写回原始的响应流
        memoryStream.Seek(0, SeekOrigin.Begin);
        await memoryStream.CopyToAsync(originalBodyStream);

        #endregion
    }
}